#include "dynamicwatermark.h"
#include "advancedprotection.h"
#include "configmanager.h"
#include "protection.h"
#include <QDateTime>
#include <QDebug>
#include <QFontDatabase>
#include <QCoreApplication>

// 静态实例
DynamicWatermark* DynamicWatermark::s_instance = nullptr;

DynamicWatermark& DynamicWatermark::instance()
{
    if (!s_instance) {
        s_instance = new DynamicWatermark();
    }
    return *s_instance;
}

DynamicWatermark::DynamicWatermark(QObject *parent)
    : QObject(parent)
    , m_updateTimer(new QTimer(this))
{

    // 初始化算法状态
    m_algorithmState.seed = generateHardwareSeed();
    m_algorithmState.algorithmIndex = m_algorithmState.seed % 5; // 5种算法
    m_algorithmState.lastUpdate = QDateTime::currentMSecsSinceEpoch();

    // 设置默认配置
    m_config.style = static_cast<WatermarkStyle>(selectBestAlgorithm());
    m_config.opacity = getTimeDependentParameter(128, 50);
    m_config.fontSize = getTimeDependentParameter(36, 12);
    m_config.dynamicPosition = true;
    m_config.timeBasedContent = true;
    m_config.hardwareBased = true;

    // 连接定时器
    connect(m_updateTimer, &QTimer::timeout, this, &DynamicWatermark::updateAlgorithm);

    // 启动算法更新定时器 (每15-45分钟更新一次)
    int updateInterval = QRandomGenerator::global()->bounded(900000, 2700000);
    m_updateTimer->start(updateInterval);

}

DynamicWatermark::~DynamicWatermark()
{
}

bool DynamicWatermark::shouldApplyWatermark()
{

    // 多层验证替代简单的isEmpty()检查
    AdvancedProtection::ValidationResult validation = AdvancedProtection::instance().validateLicense();

    // 基础判定
    bool needWatermark = !validation.isValid;

    // 添加时间因素
    if (m_config.timeBasedContent) {
        qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
        qint64 timeMod = currentTime / (1000 * 60 * 60); // 每小时变化
        if (timeMod % 3 == 0 && validation.trustLevel > 40 && validation.trustLevel < 60) {
            needWatermark = true; // 时间触发的水印
        }
    }

    // 硬件绑定因素
    if (m_config.hardwareBased && !AdvancedProtection::instance().validateHardwareBinding()) {
        needWatermark = true;
    }

    // 算法妥协检测
    if (isAlgorithmCompromised()) {
        needWatermark = true;
        rotateAlgorithm();
    }

    // 反调试触发
    if (!AdvancedProtection::instance().detectDebuggingAttempts()) {
        needWatermark = true;
    }

    // 随机噪声 - 增加分析难度
    int randomNoise = QRandomGenerator::global()->bounded(100);
    if (randomNoise < 5) { // 5%概率
        needWatermark = !needWatermark;
        QTimer::singleShot(QRandomGenerator::global()->bounded(100, 500), [this, needWatermark]() mutable {
            // 短暂延迟后恢复正常逻辑
        });
    }


    return needWatermark;
}

void DynamicWatermark::applyWatermark(QImage& image)
{
    if (!shouldApplyWatermark()) {
        return;
    }

    QPainter painter(&image);
    applyWatermark(painter, image.rect());
}

void DynamicWatermark::applyWatermark(QPainter& painter, const QRect& rect)
{
    if (!shouldApplyWatermark()) {
        return;
    }


    QString watermarkText = generateWatermarkText();

    // 根据当前算法应用不同样式的水印
    switch (m_config.style) {
    case Classic:
        applyClassicWatermark(painter, rect, watermarkText);
        break;
    case Modern:
        applyModernWatermark(painter, rect, watermarkText);
        break;
    case Minimal:
        applyMinimalWatermark(painter, rect, watermarkText);
        break;
    case Security:
        applySecurityWatermark(painter, rect, watermarkText);
        break;
    case Custom:
        applyCustomWatermark(painter, rect, watermarkText);
        break;
    }

    // 添加隐蔽标记
    embedInvisibleMarkers(painter, rect);

    // 添加噪声和诱饵水印
    if (QRandomGenerator::global()->bounded(100) < 30) { // 30%概率
        addNoisyWatermarks(painter, rect);
    }

    if (QRandomGenerator::global()->bounded(100) < 20) { // 20%概率
        addDecoyWatermarks(painter, rect);
    }

    emit watermarkApplied(QString("Style_%1").arg(m_config.style));
}

QString DynamicWatermark::generateWatermarkText()
{
    QString baseText = AdvancedProtection::instance().generateDynamicWatermark();

    if (m_config.timeBasedContent) {
        // 添加时间基础修饰符
        QString timeModifier = getTimeBasedModifier();
        baseText += " " + timeModifier;
    }

    if (m_config.hardwareBased) {
        // 添加硬件基础修饰符
        QString hwSeed = getHardwareBasedSeed();
        baseText += QString(" [%1]").arg(hwSeed.right(4));
    }

    return baseText;
}

QFont DynamicWatermark::generateWatermarkFont()
{
    QStringList fontFamilies = {"Arial", "Microsoft YaHei", "Times New Roman", "Courier New"};
    QString family = fontFamilies[m_algorithmState.seed % fontFamilies.size()];

    int size = m_config.fontSize;
    if (m_config.dynamicPosition) {
        size = getTimeDependentParameter(m_config.fontSize, 8);
    }

    QFont font(family, size);
    font.setBold(QRandomGenerator::global()->bounded(2) == 0);
    font.setItalic(QRandomGenerator::global()->bounded(3) == 0);

    return font;
}

QColor DynamicWatermark::generateWatermarkColor()
{
    if (m_config.dynamicPosition) {
        // 动态颜色生成
        int r = getTimeDependentParameter(m_config.color.red(), 50);
        int g = getTimeDependentParameter(m_config.color.green(), 50);
        int b = getTimeDependentParameter(m_config.color.blue(), 50);
        int a = getTimeDependentParameter(m_config.opacity, 30);
        return QColor(r, g, b, a);
    }

    return QColor(m_config.color.red(), m_config.color.green(),
                  m_config.color.blue(), m_config.opacity);
}

// === 私有实现函数 ===

void DynamicWatermark::applyClassicWatermark(QPainter& painter, const QRect& rect, const QString& text)
{
    painter.save();

    QFont font = generateWatermarkFont();
    painter.setFont(font);
    painter.setPen(generateWatermarkColor());
    painter.setRenderHint(QPainter::Antialiasing, m_config.antiAliasing);

    // 生成动态位置
    DynamicParams params = generateDynamicParams(rect, m_config.gridX * m_config.gridY);

    for (int i = 0; i < params.positions.size(); ++i) {
        painter.save();

        painter.translate(params.positions[i]);
        painter.rotate(params.rotations[i]);
        painter.setOpacity(params.opacities[i] / 255.0);

        QRect textRect = painter.fontMetrics().boundingRect(text);
        textRect.moveCenter(QPoint(0, 0));
        painter.drawText(textRect, Qt::AlignCenter, text);

        painter.restore();
    }

    painter.restore();
}

void DynamicWatermark::applyModernWatermark(QPainter& painter, const QRect& rect, const QString& text)
{
    painter.save();

    // 现代风格 - 使用渐变和阴影效果
    QFont font = generateWatermarkFont();
    font.setPointSize(font.pointSize() * 1.2); // 稍大
    painter.setFont(font);

    QLinearGradient gradient(0, 0, 100, 100);
    QColor baseColor = generateWatermarkColor();
    gradient.setColorAt(0, baseColor);
    gradient.setColorAt(1, QColor(baseColor.red(), baseColor.green(), baseColor.blue(), baseColor.alpha() / 2));
    painter.setPen(QPen(QBrush(gradient), 2));

    DynamicParams params = generateDynamicParams(rect, m_config.gridX * m_config.gridY);

    for (int i = 0; i < params.positions.size(); ++i) {
        painter.save();

        painter.translate(params.positions[i]);
        painter.rotate(params.rotations[i]);

        // 绘制阴影
        painter.setPen(QColor(0, 0, 0, 30));
        painter.drawText(2, 2, text);

        // 绘制主文本
        painter.setPen(QPen(QBrush(gradient), 1));
        painter.drawText(0, 0, text);

        painter.restore();
    }

    painter.restore();
}

void DynamicWatermark::applyMinimalWatermark(QPainter& painter, const QRect& rect, const QString& text)
{
    painter.save();

    // 简约风格 - 小尺寸，低对比度
    QFont font = generateWatermarkFont();
    font.setPointSize(qMax(12, font.pointSize() / 2)); // 小字体
    painter.setFont(font);

    QColor color = generateWatermarkColor();
    color.setAlpha(color.alpha() / 2); // 更透明
    painter.setPen(color);

    // 只在角落放置少量水印
    QVector<QPoint> cornerPositions = {
        rect.topLeft() + QPoint(20, 30),
        rect.topRight() + QPoint(-100, 30),
        rect.bottomLeft() + QPoint(20, -20),
        rect.bottomRight() + QPoint(-100, -20)
    };

    for (const QPoint& pos : cornerPositions) {
        painter.drawText(pos, text);
    }

    painter.restore();
}

void DynamicWatermark::applySecurityWatermark(QPainter& painter, const QRect& rect, const QString& text)
{
    painter.save();

    // 安全风格 - 多层，难以移除
    QFont font = generateWatermarkFont();
    painter.setFont(font);

    // 多层绘制
    QVector<QColor> colors = {
        QColor(255, 0, 0, 40),    // 红色层
        QColor(0, 255, 0, 40),    // 绿色层
        QColor(0, 0, 255, 40),    // 蓝色层
        generateWatermarkColor()   // 主层
    };

    DynamicParams params = generateDynamicParams(rect, m_config.gridX * m_config.gridY * 2); // 双倍密度

    for (int layer = 0; layer < colors.size(); ++layer) {
        painter.setPen(colors[layer]);

        for (int i = layer; i < params.positions.size(); i += colors.size()) {
            painter.save();
            painter.translate(params.positions[i]);
            painter.rotate(params.rotations[i] + layer * 15); // 每层不同角度

            QRect textRect = painter.fontMetrics().boundingRect(text);
            textRect.moveCenter(QPoint(0, 0));
            painter.drawText(textRect, Qt::AlignCenter, text);

            painter.restore();
        }
    }

    painter.restore();
}

void DynamicWatermark::applyCustomWatermark(QPainter& painter, const QRect& rect, const QString& text)
{
    // 自定义算法 - 结合多种技术
    applyClassicWatermark(painter, rect, text);

    if (QRandomGenerator::global()->bounded(2) == 0) {
        applyModernWatermark(painter, rect, text);
    }

}

void DynamicWatermark::embedInvisibleMarkers(QPainter& painter, const QRect& rect)
{
    // 嵌入不可见标记，用于检测水印移除尝试
    painter.save();

    // 使用极低对比度的像素
    painter.setPen(QColor(255, 255, 255, 1));

    // 在随机位置绘制单个像素
    for (int i = 0; i < 20; ++i) {
        int x = QRandomGenerator::global()->bounded(rect.width());
        int y = QRandomGenerator::global()->bounded(rect.height());
        painter.drawPoint(rect.topLeft() + QPoint(x, y));
    }

    painter.restore();
}

void DynamicWatermark::addNoisyWatermarks(QPainter& painter, const QRect& rect)
{
    // 添加噪声水印来干扰自动移除工具
    painter.save();

    QStringList noiseTexts = {"X", "Y", "Z", "•", "◦", "∘"};
    painter.setPen(QColor(200, 200, 200, 20));

    for (int i = 0; i < 50; ++i) {
        int x = QRandomGenerator::global()->bounded(rect.width());
        int y = QRandomGenerator::global()->bounded(rect.height());
        QString noiseText = noiseTexts[QRandomGenerator::global()->bounded(noiseTexts.size())];
        painter.drawText(rect.topLeft() + QPoint(x, y), noiseText);
    }

    painter.restore();
}

void DynamicWatermark::addDecoyWatermarks(QPainter& painter, const QRect& rect)
{
    // 添加诱饵水印 - 看起来像主要水印但实际不是
    painter.save();

    QStringList decoyTexts = {"Sample", "Demo", "Preview", "Test"};
    painter.setPen(QColor(150, 150, 150, 60));
    painter.setFont(QFont("Arial", 24));

    for (const QString& decoy : decoyTexts) {
        int x = QRandomGenerator::global()->bounded(rect.width() - 100);
        int y = QRandomGenerator::global()->bounded(rect.height() - 50);
        painter.save();
        painter.translate(x, y);
        painter.rotate(QRandomGenerator::global()->bounded(-60, 60));
        painter.drawText(0, 0, decoy);
        painter.restore();
    }

    painter.restore();
}

DynamicWatermark::WatermarkStyle DynamicWatermark::selectBestAlgorithm()
{
    // 基于多种因素选择最佳算法
    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    QString hwId = Protection::machineIDHashKey();

    uint hash = qHash(QString("%1_%2").arg(currentTime / (1000 * 60 * 60)).arg(hwId));
    return static_cast<WatermarkStyle>(hash % 5);
}

void DynamicWatermark::rotateAlgorithm()
{
    m_algorithmState.algorithmIndex = (m_algorithmState.algorithmIndex + 1) % 5;
    m_config.style = static_cast<WatermarkStyle>(m_algorithmState.algorithmIndex);
    m_algorithmState.lastUpdate = QDateTime::currentMSecsSinceEpoch();

    emit algorithmCompromised(QString("Algorithm_%1").arg(m_algorithmState.algorithmIndex));
}

bool DynamicWatermark::isAlgorithmCompromised()
{
    // 检测算法是否可能被破解者分析
    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    qint64 timeSinceLastUpdate = currentTime - m_algorithmState.lastUpdate;

    // 如果算法使用时间过长，认为可能被分析
    return timeSinceLastUpdate > (1000 * 60 * 60 * 2); // 2小时
}

DynamicWatermark::DynamicParams DynamicWatermark::generateDynamicParams(const QRect& rect, int count)
{
    DynamicParams params;

    for (int i = 0; i < count; ++i) {
        // 动态位置
        int x = (rect.width() / m_config.gridX) * (i % m_config.gridX) +
                rect.width() / (m_config.gridX * 2);
        int y = (rect.height() / m_config.gridY) * (i / m_config.gridX) +
                rect.height() / (m_config.gridY * 2);

        if (m_config.dynamicPosition) {
            x += QRandomGenerator::global()->bounded(-50, 50);
            y += QRandomGenerator::global()->bounded(-30, 30);
        }

        params.positions.append(rect.topLeft() + QPoint(x, y));

        // 动态旋转
        int rotation = m_config.rotation;
        if (m_config.dynamicPosition) {
            rotation += QRandomGenerator::global()->bounded(-15, 15);
        }
        params.rotations.append(rotation);

        // 动态透明度
        int opacity = m_config.opacity;
        if (m_config.dynamicPosition) {
            opacity = getTimeDependentParameter(opacity, 40);
        }
        params.opacities.append(opacity);
    }

    return params;
}

QString DynamicWatermark::getHardwareBasedSeed()
{
    return Protection::machineIDHashKey();
}

uint32_t DynamicWatermark::generateHardwareSeed()
{
    QString hwId = getHardwareBasedSeed();
    QByteArray hash = QCryptographicHash::hash(hwId.toUtf8(), QCryptographicHash::Md5);

    uint32_t seed = 0;
    for (int i = 0; i < qMin(4, hash.size()); ++i) {
        seed = (seed << 8) | static_cast<uint8_t>(hash[i]);
    }

    return seed;
}

QString DynamicWatermark::getTimeBasedModifier()
{
    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    qint64 hourMod = (currentTime / (1000 * 60 * 60)) % 24;

    QStringList modifiers = {
        "TRIAL", "DEMO", "PREVIEW", "SAMPLE",
        "EVALUATION", "TEST", "UNREGISTERED"
    };

    return modifiers[hourMod % modifiers.size()];
}

int DynamicWatermark::getTimeDependentParameter(int base, int variation)
{
    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    qint64 timeSeed = currentTime / (1000 * 60 * 15); // 每15分钟变化

    uint hash = qHash(QString::number(timeSeed) + QString::number(m_algorithmState.seed));
    int offset = (hash % (variation * 2)) - variation;

    return qMax(1, base + offset);
}

void DynamicWatermark::updateAlgorithm()
{

    if (isAlgorithmCompromised()) {
        rotateAlgorithm();
    }

    // 更新配置参数
    m_config.opacity = getTimeDependentParameter(128, 30);
    m_config.fontSize = getTimeDependentParameter(36, 8);

    // 随机化下次更新间隔
    int nextInterval = QRandomGenerator::global()->bounded(900000, 2700000); // 15-45分钟
    m_updateTimer->start(nextInterval);

}

void DynamicWatermark::performSecurityCheck()
{
    if (!validateWatermarkIntegrity()) {
        emit tamperingDetected("Watermark integrity violation");
        respondToTamperingAttempt();
    }
}

bool DynamicWatermark::validateWatermarkIntegrity()
{
    // 验证水印系统的完整性
    return true; // 简化实现
}

void DynamicWatermark::respondToTamperingAttempt()
{

    // 切换到更强的安全模式
    m_config.style = Security;
    m_algorithmState.isCompromised = true;

    // 提高水印强度
    m_config.opacity = qMin(255, m_config.opacity + 50);
    m_config.gridX = qMin(5, m_config.gridX + 1);
    m_config.gridY = qMin(5, m_config.gridY + 1);
}